<template>
  <div class="map-container">
    <!-- 地图容器 -->
    <div id="amap" class="amap-container"></div>
    
    <!-- 悬浮搜索框 -->
    <div class="search-bar">
      <el-input
        v-model="searchAddress"
        placeholder="输入地址搜索（如：北京市天安门）"
        clearable
        @keyup.enter="handleAddressSearch"
        style="width: 350px;"
      />
      <el-button type="primary" @click="handleAddressSearch" :loading="searching">
        搜索
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';

// 响应式数据
const map = ref(null);        // 地图实例
const markers = ref([]);     // 存储所有标记
const jobData = ref([]);     // 存储职位数据
const amapWebKey = ref('');  // 高德地图 Web Key
const searchAddress = ref(''); // 搜索地址
const searching = ref(false);  // 搜索中状态

const { proxy } = getCurrentInstance();

// 初始化地图
onMounted(async () => {
  try {
    // 1. 获取高德 Web Key
    const res = await proxy.$axios.get('/web-key/');
    amapWebKey.value = res.data.amap_web_key;

    // 2. 加载高德地图 API 和插件
    await loadAmapScript();

    // 3. 创建地图实例
    map.value = new window.AMap.Map('amap', {
      zoom: 13,
      center: [116.39748, 39.90882], // 北京为中心
      resizeEnable: true
    });

    // 4. 添加地图控件（缩放、定位）
    map.value.addControl(new window.AMap.Scale());
    map.value.addControl(new window.AMap.ToolBar({ position: 'RB' }));
    map.value.addControl(new window.AMap.Geolocation({
      enableHighAccuracy: true,
      showButton: true,
      zoomToAccuracy: true
    }));

    // 5. 加载职位数据并渲染标注
    await loadJobMarkers();

  } catch (error) {
    console.error('地图初始化失败：', error);
    ElMessage.error('地图加载失败，请刷新重试！');
  }
});

// 销毁地图（避免内存泄漏）
onUnmounted(() => {
  if (map.value) {
    map.value.destroy();
    map.value = null;
  }
});

// 动态加载高德地图 API
const loadAmapScript = () => {
  return new Promise((resolve, reject) => {
    // 如果已经加载且插件已加载，直接返回
    if (window.AMap && window.AMap.Scale && window.AMap.ToolBar && window.AMap.Geolocation && window.AMap.InfoWindow) {
      resolve();
      return;
    }

    // 加载主 API
    const loadMainAPI = () => {
      return new Promise((resolveMain, rejectMain) => {
        if (window.AMap && window.AMap.plugin) {
          resolveMain();
          return;
        }
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = `https://webapi.amap.com/maps?v=2.0&key=${amapWebKey.value}`;
        script.onload = () => {
          // 等待 AMap 对象完全初始化
          const checkAMap = setInterval(() => {
            if (window.AMap && window.AMap.plugin) {
              clearInterval(checkAMap);
              resolveMain();
            }
          }, 50);
          // 超时保护（5秒）
          setTimeout(() => {
            clearInterval(checkAMap);
            if (window.AMap && window.AMap.plugin) {
              resolveMain();
            } else {
              rejectMain('高德 API 初始化超时');
            }
          }, 5000);
        };
        script.onerror = () => rejectMain('高德 API 加载失败');
    document.head.appendChild(script);
  });
};

    // 加载插件
    const loadPlugins = () => {
      return new Promise((resolvePlugins, rejectPlugins) => {
        if (window.AMap.Scale && window.AMap.ToolBar && window.AMap.Geolocation && window.AMap.InfoWindow) {
          resolvePlugins();
          return;
        }

        // 确保 AMap 对象已存在
        if (!window.AMap || !window.AMap.plugin) {
          rejectPlugins('高德地图 API 未正确加载');
          return;
        }

        // 需要加载的插件列表
        const plugins = ['AMap.Scale', 'AMap.ToolBar', 'AMap.Geolocation', 'AMap.InfoWindow'];
        
        window.AMap.plugin(plugins, (err) => {
          if (err) {
            rejectPlugins('插件加载失败：' + err);
            return;
          }
          resolvePlugins();
        });
      });
    };

    // 先加载主 API，再加载插件
    loadMainAPI()
      .then(() => loadPlugins())
      .then(() => resolve())
      .catch(reject);
  });
};

// 加载职位数据并渲染标注
const loadJobMarkers = async () => {
  try {
    // 调用后端接口获取职位数据
    const res = await proxy.$axios.get('/job-location/');
    if (res.data.status === 'success' && res.data.data && res.data.data.length) {
      jobData.value = res.data.data;
      clearMarkers(); // 先清除已有标注

      // 批量创建职位标记
      jobData.value.forEach((job) => {
        const lng = Number(job.longitude);
        const lat = Number(job.latitude);
        if (isNaN(lng) || isNaN(lat)) return;

        // 获取职位信息
        const title = job.title || '未知职位';
        const salary = job.salary_range || job.salary || '面议';
        const company = job.company_name || job.company?.name || job.company || '未知公司';
        
        // 提取技术栈（从标题中提取，或使用其他字段）
        const techStack = title.includes('java') ? 'java' : 
                         title.includes('vue') ? 'vue' : 
                         title.includes('前端') ? '前端' : 
                         title.includes('后端') ? '后端' : 
                         title.split(/[+/、]/)[0] || '开发';

        // 创建自定义 HTML 内容（青色气泡样式）
        const content = document.createElement('div');
        content.className = 'job-marker-bubble';
        content.innerHTML = `
          <div class="job-bubble-content">
            <div class="job-tech">${techStack}</div>
            <div class="job-salary-text">${salary}</div>
            <div class="job-company-text">${company.length > 8 ? company.substring(0, 8) + '...' : company}</div>
          </div>
        `;

        // 创建自定义标记
        const marker = new window.AMap.Marker({
          position: [lng, lat],
          content: content,
          offset: new window.AMap.Pixel(-60, -30), // 调整偏移，使气泡底部指向位置
          map: map.value,
          extData: job // 存储职位数据，点击时使用
        });

        // 标记类型为职位
        markers.value.push({ type: 'job', marker: marker });

        // 标记点击事件：显示详细信息窗口
        marker.on('click', (e) => {
          const job = e.target.getExtData();
          const infoWindow = new window.AMap.InfoWindow({
            content: `
              <div class="custom-info-window">
                <div class="job-title">${job.title || '未知职位'}</div>
                <div class="job-salary">薪资：${job.salary_range || job.salary || '面议'}</div>
                <div class="job-company">公司：${job.company_name || job.company?.name || job.company || '未知公司'}</div>
                <div class="job-address">地址：${job.work_city || job.address || '未知'}</div>
              </div>
            `,
            offset: new window.AMap.Pixel(0, -30)
          });
          // 使用 open 方法打开信息窗口
          infoWindow.open(map.value, [lng, lat]);
        });
      });

      ElMessage.success(`成功加载 ${jobData.value.length} 个职位标注！`);
    } else {
      ElMessage.info('暂无职位数据！');
    }
  } catch (error) {
    console.error('加载职位标注失败：', error);
    ElMessage.error('职位数据加载失败，请重试！');
  }
};

// 清除所有标记
const clearMarkers = () => {
  markers.value.forEach(marker => {
    marker.remove();
  });
  markers.value = [];
};

// 地址搜索功能
const handleAddressSearch = async () => {
  if (!searchAddress.value.trim()) {
    ElMessage.warning('请输入地址！');
    return;
  }

  if (!map.value) {
    ElMessage.warning('地图尚未加载完成，请稍候再试！');
    return;
  }

  searching.value = true;

  try {
    // 调用后端地理编码接口
    const res = await proxy.$axios.get('/geocode/', {
      params: { address: searchAddress.value.trim() }
    });

    // 检查后端返回的错误信息
    if (res.data.error) {
      ElMessage.error(res.data.error);
      searching.value = false;
      return;
    }

    // 检查高德 API 返回的状态
    if (res.data.status === '1' && res.data.geocodes && res.data.geocodes.length > 0) {
      const geocode = res.data.geocodes[0];
      const [lng, lat] = geocode.location.split(',').map(Number);
      const formattedAddress = geocode.formatted_address || geocode.formattedAddress || searchAddress.value.trim();

      // 清除已有的地址标注（保留职位标注）
      clearAddressMarkers();

      // 更新地图中心点并适当缩放
      map.value.setCenter([lng, lat]);
      map.value.setZoom(15);

      // 添加地址标注点
      const marker = new window.AMap.Marker({
        position: [lng, lat],
        title: formattedAddress,
        map: map.value,
        icon: new window.AMap.Icon({
          size: new window.AMap.Size(32, 32),
          image: 'https://a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png'
        })
      });
      markers.value.push({ type: 'address', marker: marker });

      // 打开信息弹窗
      const infoWindow = new window.AMap.InfoWindow({
        content: `
          <div style="padding: 10px; min-width: 220px;">
            <h4 style="margin: 0 0 8px 0; font-size: 14px; font-weight: 600;">${formattedAddress}</h4>
            <p style="margin: 4px 0; color: #666; font-size: 12px;">经纬度：${lng.toFixed(6)}, ${lat.toFixed(6)}</p>
            <p style="margin: 4px 0; color: #999; font-size: 12px;">${geocode.province || ''} ${geocode.city || ''} ${geocode.district || ''}</p>
          </div>
        `,
        offset: new window.AMap.Pixel(0, -30)
      });

      // 使用 open 方法打开信息窗口
      infoWindow.open(map.value, [lng, lat]);

      // 调用后端存储接口保存地址经纬度（可选）
      try {
        await proxy.$axios.post('/save-location/', {
          address: formattedAddress,
          longitude: lng,
          latitude: lat
        });
      } catch (saveError) {
        console.warn('存储地址经纬度失败（不影响使用）:', saveError.response?.data?.error || saveError.message);
      }

      ElMessage.success('地址搜索成功！');
    } else {
      const errorMsg = res.data.info || '地址解析失败，请检查输入！';
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error('地址搜索失败：', error);
    const errorMsg = error.response?.data?.error || error.message || '网络错误，请重试！';
    ElMessage.error(errorMsg);
  } finally {
    searching.value = false;
  }
};

// 清除地址标注（保留职位标注）
const clearAddressMarkers = () => {
  const addressMarkers = markers.value.filter(item => item.type === 'address');
  addressMarkers.forEach(({ marker }) => {
    marker.remove();
  });
  markers.value = markers.value.filter(item => item.type !== 'address');
};
</script>

<style scoped>
/* 地图容器占满整个页面 */
.map-container {
  position: relative;
  width: 100vw;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow: hidden;
}

/* 地图容器样式 */
.amap-container {
  width: 100%;
  height: 100%;
  border: none;
  border-radius: 0;
  position: relative;
  z-index: 1;
}

/* 悬浮搜索框样式 */
.search-bar {
  position: absolute;
  top: 4px; /* 避开顶部导航栏（约64px）并保留间距 */
  left: 10px;
  z-index: 900;
  display: flex;
  align-items: center;
  gap: 10px;
  background: rgba(255, 255, 255, 0.95);
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  backdrop-filter: blur(10px);
  pointer-events: auto;
  min-width: 320px;
}

@media (max-width: 768px) {
  .search-bar {
    top: 88px;
    left: 16px;
    right: 16px;
    min-width: auto;
    width: calc(100% - 32px);
    flex-wrap: wrap;
    padding: 12px 16px;
  }
}
</style>

<style>
/* 全局样式：用于动态创建的职位标注气泡（通过 DOM 创建，不在组件模板中） */

/* 职位标注气泡样式（全局样式，因为是通过 DOM 动态创建的） */
.job-marker-bubble {
  background: linear-gradient(135deg, #00bcd4 0%, #0097a7 100%);
  border-radius: 8px;
  padding: 8px 12px;
  box-shadow: 0 2px 8px rgba(0, 188, 212, 0.3);
  cursor: pointer;
  transition: all 0.3s ease;
  min-width: 100px;
  max-width: 180px;
  position: relative;
}

.job-marker-bubble:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 188, 212, 0.4);
}

.job-marker-bubble::after {
  content: '';
  position: absolute;
  bottom: -8px;
  left: 50%;
  transform: translateX(-50%);
  width: 0;
  height: 0;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-top: 8px solid #0097a7;
}

.job-bubble-content {
  color: white;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

.job-tech {
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 4px;
  color: #ffffff;
  line-height: 1.2;
}

.job-salary-text {
  font-size: 12px;
  font-weight: 500;
  margin-bottom: 3px;
  color: #ffffff;
  opacity: 0.95;
  line-height: 1.2;
}

.job-company-text {
  font-size: 11px;
  color: #ffffff;
  opacity: 0.85;
  line-height: 1.2;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 自定义信息窗口样式（点击后显示，由高德地图 API 创建） */
.custom-info-window {
  background-color: #00bcd4;
  color: white;
  padding: 12px 16px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  min-width: 220px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', sans-serif;
}

.custom-info-window .job-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #ffffff;
}

.custom-info-window .job-salary {
  font-size: 14px;
  margin-bottom: 6px;
  color: #ffffff;
  opacity: 0.95;
}

.custom-info-window .job-company,
.custom-info-window .job-address {
  font-size: 13px;
  opacity: 0.9;
  margin-bottom: 4px;
  color: #ffffff;
}
</style>